package org.groupg.practice;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.AllValue;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.update.Update;

public class SqlModifier {
    public static String addWhereCondition(String originalSql, String newCondition)
            throws JSQLParserException {

        Statement stmt = CCJSqlParserUtil.parse(originalSql);
        Expression newExpr = CCJSqlParserUtil.parseCondExpression(newCondition);

        if (stmt instanceof Select select) {
            PlainSelect ps = (PlainSelect) select;
            Expression existingWhere = ps.getWhere();
            // 合并新旧条件
            ps.setWhere(existingWhere == null ?
                    newExpr :
                    new AndExpression(existingWhere, newExpr)
            );
        } else if (stmt instanceof Update update) {
            Expression existingWhere = update.getWhere();
            update.setWhere(existingWhere == null ?
                    newExpr :
                    new AndExpression(existingWhere, newExpr)
            );
        }
        // DELETE语句处理类似
        return stmt.toString();
    }

    public static String addInsertColumn(String originalSql, String columnName, String columnValue)
            throws JSQLParserException {

        Statement stmt = CCJSqlParserUtil.parse(originalSql);
        if (stmt instanceof Insert insert) {

            // 添加列名
            insert.getColumns().add(new Column(columnName));

            insert.getValues().addExpressions(new StringValue(columnValue));
//            // 添加值（假设是简单值列表）
//            if (insert.getValues().getExpressions() != null) {
//                ExpressionList<StringValue> list = (ExpressionList<StringValue>) insert.getValues().getExpressions();
//                list.add(new StringValue(columnValue));
//            }
        }
        return stmt.toString();
    }

    public static void main(String[] args) throws JSQLParserException {
        String originalSql = "INSERT INTO users (name) VALUES ('John')";
        String modifiedSql = addInsertColumn(originalSql, "age", "25");
        System.out.println(modifiedSql);
        originalSql = "SELECT * FROM users";
        modifiedSql = addWhereCondition(originalSql, "age > 18");
// 结果：SELECT * FROM users WHERE age > 18
        System.out.println(modifiedSql);
    }
}